package com.pzh.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.pzh.usercenter.common.ErrorCode;
import com.pzh.usercenter.contant.UserConstant;
import com.pzh.usercenter.exception.BusinessException;
import com.pzh.usercenter.model.domain.User;
import com.pzh.usercenter.service.UserService;
import com.pzh.usercenter.mapper.UserMapper;
import com.pzh.usercenter.utils.Algorithm;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author fc3379757631
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-11-15 22:36:53
 */
@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Resource
    private UserMapper userMapper;

    //使用自定义 RedisTemplate 序列化器
    @Resource
    private RedisTemplate<String, Object> redisTemplate;


    //盐值
    private static final String SALT = "pzh";

    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1、校验
        if (StringUtils.isAllBlank(userAccount, userPassword, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户长度过短");
        }
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "密码过短");
        }
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号过长");
        }
        //账户不包含特殊字符
        //正则表达式：
        //\\pP：代表所有的标点符号（Punctuation）。在Unicode标准中，标点符号是一类特定的字符，包括句号、逗号、问号等。
        //\\pS：代表所有的符号（Symbol）。这包括了数学符号、货币符号、箭头等不属于标点符号的特殊字符。
        //\\s+：代表一个或多个空白字符，包括空格、制表符、换行符等。+表示前面的字符（在这个情况下是任何空白字符）可以出现一次或多次。
        String validPattern = "\\pP|\\pS|\\s+";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户包含特殊字符");
        }
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不同");
        }
        //账号不能重复
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //查询账户是否相等
        userQueryWrapper.eq("account", userAccount);
        long count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            //账户已存在
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号已存在");
        }

        //星球编号不能重复
        userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("planetCode", planetCode);
        count = userMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            //编号已存在
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "星球编号已存在");
        }

        //2、加密
        //加盐
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(newPassword);
        user.setPlanetCode(planetCode);
        boolean saveResult = this.save(user);
        if (!saveResult) {
            //保存失败,结果为null
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户保存失败");
        }

        return user.getId();
    }

    @Override
    public User doLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //验证
        if (StringUtils.isAllBlank(userAccount, userPassword)) {
            return null;
        }
        if (userAccount.length() < 4) {
            return null;
        }
        if (userPassword.length() < 8) {
            return null;
        }
        //账户不包含特殊字符
        //正则表达式：
        //\\pP：代表所有的标点符号（Punctuation）。在Unicode标准中，标点符号是一类特定的字符，包括句号、逗号、问号等。
        //\\pS：代表所有的符号（Symbol）。这包括了数学符号、货币符号、箭头等不属于标点符号的特殊字符。
        //\\s+：代表一个或多个空白字符，包括空格、制表符、换行符等。+表示前面的字符（在这个情况下是任何空白字符）可以出现一次或多次。
        String validPattern = "[`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        Matcher matcher = Pattern.compile(validPattern).matcher(userAccount);
        if (matcher.find()) {
            return null;
        }

        //2、加密
        //加盐
        String newPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //查询账户
        // Q:用户被删除还可以被查到吗?
        // S:mybatis plus 提供便捷的逻辑删除支持，自动处理逻辑删除字段
        userQueryWrapper.eq("userAccount", userAccount);
        userQueryWrapper.eq("userPassword", newPassword);

        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            //账号或密码错误
            log.info("The user login fails, and the account and password do not match");
            return null;
        }

        //3、用户脱敏
        //如果使用多了可以封装到DTO
        User safetyUser = getSafetyUser(user);

        //4、设置用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, safetyUser);

        return safetyUser;
    }

    /**
     * 用户脱敏
     *
     * @param originUser
     * @return
     */
    public User getSafetyUser(User originUser) {
        if (originUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User safetyUser = new User();
        safetyUser.setId(originUser.getId());
        safetyUser.setUsername(originUser.getUsername());
        safetyUser.setUserAccount(originUser.getUserAccount());
        safetyUser.setAvatarUrl(originUser.getAvatarUrl());
        safetyUser.setGender(originUser.getGender());
        safetyUser.setPhone(originUser.getPhone());
        safetyUser.setEmail(originUser.getEmail());
        safetyUser.setUserStatus(originUser.getUserStatus());
        safetyUser.setCreateTime(originUser.getCreateTime());
        safetyUser.setUserRole(originUser.getUserRole());
        safetyUser.setPlanetCode(originUser.getPlanetCode());
        safetyUser.setTags(originUser.getTags());
        return safetyUser;
    }

    /**
     * 用户注销
     *
     * @param request
     * @return
     */
    public int userLogout(HttpServletRequest request) {
        //移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return 1;
    }

    /**
     * 根据标签搜索用户 (内存查询)
     *
     * @param tagNameList 用户拥有的标签
     * @return
     */
    @Override
    public List<User> searchUsersByTags(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //1、先查询所有用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        List<User> userList = userMapper.selectList(queryWrapper);
        Gson gson = new Gson();
        //在内存中判断是否包含要求的标签
        return userList.stream().filter(user -> {
            String tagsStr = user.getTags();
            Set<String> tempTagNameSet = gson.fromJson(tagsStr, new TypeToken<Set<String>>() {
            }.getType());
            tempTagNameSet = Optional.ofNullable(tempTagNameSet).orElse(new HashSet<>());
            for (String tagName : tagNameList) {
                if (!tempTagNameSet.contains(tagName)) {
                    return false;
                }
            }
            return true;
        }).map(this::getSafetyUser).collect(Collectors.toList());
    }

    /**
     * 更新 loginUser 信息为 user
     *
     * @param user
     * @param loginUser
     * @return
     */
    @Override
    public int updateUser(User user, User loginUser) {
        long userId = user.getId();
        if (userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // todo 补充校验，如果用户没有传任何要更新的值，就直接报错

        //非管理员 且 该登录用户非本人
        if (!isAdmin(loginUser) && userId != loginUser.getId()) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        //管理员,允许更新任意用户信息
        //非管理员，仅能更新当前用户（自己）信息
        User oldUser = userMapper.selectById(userId);
        if (oldUser == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //更新 loginUser 信息为 user
        return userMapper.updateById(user);
    }

    @Override
    public boolean isAdmin(HttpServletRequest request) {
        //仅管理员可查询
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public boolean isAdmin(User user) {
        return user != null && user.getUserRole() == UserConstant.ADMIN_ROLE;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        if (request == null) {
            return null;
        }
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        //没获取到登录态
        if (userObj == null) {
            throw new BusinessException(ErrorCode.NO_AUTH);
        }
        return (User) userObj;
    }

    /**
     * 获取推荐用户
     *
     * @param pageSize
     * @param pageNum
     * @param request
     * @return
     */
    @Override
    public Page<User> getRecommendUsers(long pageSize, long pageNum, HttpServletRequest request) {
        //获取用户
        User loginUser = getLoginUser(request);
        // key todo 将key变为常量
        String userKey = String.format("yupao:user:recommend:%s", loginUser.getId());
        //先查缓存
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        Page<User> userPage = (Page<User>) valueOperations.get(userKey);
        if (userPage != null) {
            //存在直接返回
            return userPage;
        }
        //不存在查数据库
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        userPage = page(new Page<>(pageNum, pageSize), queryWrapper);
        //存入redis,设置过期时间 15s
        try {
            valueOperations.set(userKey, userPage, 15, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis set key error", e);
        }
        return userPage;
    }

    /**
     * 获取最匹配用户
     *
     * @param num
     * @param loginUser
     * @return
     */
    @Override
    public List<User> matchUsers(long num, User loginUser) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //增加查询效率
        queryWrapper.select("id", "tags");
        queryWrapper.isNotNull("tags");
        List<User> userList = this.list(queryWrapper);
        String tags = loginUser.getTags();
        Gson gson = new Gson();
        List<String> tagsList = gson.fromJson(tags, new TypeToken<List<String>>() {
        }.getType());

        List<Pair<User, Long>> list = new ArrayList<>();
//        SortedMap<Integer, Long> indexDistanceMap = new TreeMap<>();
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            String userTags = user.getTags();
            if (StringUtils.isBlank(userTags) || user.getId() == loginUser.getId()) {
                continue;
            }
            List<String> userTagsList = gson.fromJson(userTags, new TypeToken<List<String>>() {
            }.getType());

            long distance = Algorithm.minDistance(userTagsList, tagsList);
            list.add(Pair.of(user, distance));

        }
        //查询出的User列表数据不足
        List<Pair<User, Long>> pairList = list.stream()
                .sorted((a, b) -> (int) (a.getValue() - b.getValue()))
                .limit(num).toList();
        //查询出的userId排序(编辑距离由小到大)
        List<Long> originUserIdList = pairList.stream().map(pair -> pair.getKey().getId()).toList();
        QueryWrapper<User> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", originUserIdList);
        //未按照要求排序的user列表
        Map<Long, List<User>> userListMap = this.list(queryWrapper2).stream()
                .map(user -> getSafetyUser(user))
                .collect(Collectors.groupingBy(User::getId));
        List<User> res = new ArrayList<>();
        //排序后
        for(Long userId : originUserIdList) {
            res.add(userListMap.get(userId).get(0));
        }
        return res;
    }


    /**
     * 根据标签搜索用户(SQL 查询) （弃用）
     *
     * @param tagNameList 用户拥有的标签
     * @return
     */
    @Deprecated
    private List<User> searchUsersByTagsSQL(List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // like '%java%' and like '%python%'
        for (String tagName : tagNameList) {
            queryWrapper = queryWrapper.like("tags", tagName);
        }
        List<User> userList = userMapper.selectList(queryWrapper);
        //用户脱敏
        return userList.stream().map(this::getSafetyUser).collect(Collectors.toList());
    }

}




